package org.linlinjava.litemall.admin.service;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.pagehelper.PageHelper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.util.DateUtils;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.dao.LitemallMemberOrderMapper;
import org.linlinjava.litemall.db.dao.LitemallRentOrderMapper;
import org.linlinjava.litemall.db.dao.UserMemberFreezeMapper;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.LitemallRentOrderService;
import org.linlinjava.litemall.db.service.LitemallUserService;
import org.linlinjava.litemall.db.util.BalanceConstant;
import org.linlinjava.litemall.db.util.PayStatusConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.jws.Oneway;
import java.math.BigDecimal;
import java.sql.Wrapper;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * @author Administrator
 */
@Service
public class AdminMemberOrderService {
    private final Log logger = LogFactory.getLog(AdminMemberOrderService.class);
    @Autowired
    private LitemallMemberOrderMapper memberOrderMapper;
    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private LitemallUserService userService;
    @Autowired
    private LitemallRentOrderService rentOrderService;
    @Autowired
    private UserMemberFreezeMapper userMemberFreezeMapper;

    /**
     * 后台退押金
     *
     * @param memberOrderId
     * @return
     */
    @Transactional
    public Object doRefund(Integer memberOrderId) {
        LitemallMemberOrder memberOrder = memberOrderMapper.selectByPrimaryKey(memberOrderId);
        if (memberOrder == null) {
            return ResponseUtil.fail(400, "该订单不存在");
        }
//        LitemallRentOrder rentOrder = rentOrderService.queryLastOrder(memberOrder.getUserId());
//
//        if (rentOrder != null && (!rentOrder.getRentOrderStatus().equals(RentOrderConstant.STATUS_CONFIRM_RETURN) || rentOrder.getRentOrderStatus().equals(RentOrderConstant.STATUS_CANCEL))) {
//            return ResponseUtil.fail(400, "该用户尚有待还的书，不能退款");
//        }
        boolean b = rentOrderService.queryOrderHaveNoReturnBook(memberOrder.getUserId());
        if (b){
            return ResponseUtil.fail(400, "该用户尚有待还的书，不能退款");
        }

        if (memberOrder.getPayId() != null) {// 微信退款
            WxPayRefundRequest wxPayRefundRequest = new WxPayRefundRequest();
            wxPayRefundRequest.setOutTradeNo(memberOrder.getMemberOrderSn());
            wxPayRefundRequest.setOutRefundNo("refund_" + memberOrder.getMemberOrderSn());
            // 元转成分
            Integer totalFee = memberOrder.getFinalPrice().multiply(new BigDecimal(100)).intValue();
            wxPayRefundRequest.setTotalFee(totalFee);
            wxPayRefundRequest.setRefundFee(totalFee);

            WxPayRefundResult wxPayRefundResult;
            try {
                wxPayRefundResult = wxPayService.refund(wxPayRefundRequest);
            } catch (WxPayException e) {
                logger.error(e.getMessage(), e);
                return ResponseUtil.fail(600, "订单退款失败");
            }
            if (!wxPayRefundResult.getReturnCode().equals("SUCCESS")) {
                logger.warn("refund fail: " + wxPayRefundResult.getReturnMsg());
                return ResponseUtil.fail(600, "订单退款失败");
            }
            if (!wxPayRefundResult.getResultCode().equals("SUCCESS")) {
                logger.warn("refund fail: " + wxPayRefundResult.getReturnMsg());
                return ResponseUtil.fail(600, "订单退款失败");
            }
            memberOrder.setRefundType("微信退款接口");
            memberOrder.setRefundContent(wxPayRefundResult.getRefundId());
        } else { // 余额退款
            userService.addBalance(memberOrder.getUserId(), memberOrder.getFinalPrice(), BalanceConstant.REFUND);
        }

        LocalDateTime now = LocalDateTime.now();
        // 设置订单取消状态
        memberOrder.setPayStatus(PayStatusConstant.HAS_REFUNDED);
        LitemallUser user = userService.findById(memberOrder.getUserId());
        user.setHasPayDeposit(false);
        user.setDeposit(BigDecimal.ZERO);
        userService.updateById(user);

        // 记录订单退款相关信息
        memberOrder.setRefundAmount(memberOrder.getFinalPrice());
        memberOrder.setRefundTime(now);
        memberOrderMapper.updateByPrimaryKeySelective(memberOrder);

        return ResponseUtil.ok();
    }

    /**
     * 申请退押金订单list
     *
     * @param page
     * @param limit
     * @return
     */
    public Object listRefundingDeposit(Integer page, Integer limit,String nickname,String status) {
        LitemallMemberOrderExample example = new LitemallMemberOrderExample();
        LitemallMemberOrderExample.Criteria criteria = example.createCriteria();
        if (ObjectUtil.isNotEmpty(nickname)){
            criteria.andNicknameLike("%" + nickname + "%");
        }
        if (ObjectUtil.isNotEmpty(status)){
            criteria.andPayStatusEqualTo(Integer.parseInt(status));
        }
        criteria.andDeletedEqualTo(false);
        criteria.andTypeEqualTo(2);
        criteria.andPayStatusGreaterThan(2);
        example.setOrderByClause("add_time desc");
        PageHelper.startPage(page, limit);
        List<LitemallMemberOrder> orders = memberOrderMapper.selectByExample(example);
        return ResponseUtil.okList(orders);
    }

    public Object doOfflineRefund(Integer memberOrderId) {

        LitemallMemberOrder memberOrder = memberOrderMapper.selectByPrimaryKey(memberOrderId);
        if (memberOrder == null) {
            return ResponseUtil.fail(400, "该订单不存在");
        }
//        LitemallRentOrder rentOrder = rentOrderService.queryLastOrder(memberOrder.getUserId());
//
//        if (rentOrder != null && (!rentOrder.getRentOrderStatus().equals(RentOrderConstant.STATUS_CONFIRM_RETURN) || rentOrder.getRentOrderStatus().equals(RentOrderConstant.STATUS_CANCEL))) {
//            return ResponseUtil.fail(400, "该用户尚有待还的书，不能退款");
//        }
        boolean b = rentOrderService.queryOrderHaveNoReturnBook(memberOrder.getUserId());
        if (b){
            return ResponseUtil.fail(400, "该用户尚有待还的书，不能退款");
        }


        LocalDateTime now = LocalDateTime.now();
        // 设置订单取消状态
        memberOrder.setPayStatus(PayStatusConstant.HAS_REFUNDED);
        LitemallUser user = userService.findById(memberOrder.getUserId());
        user.setHasPayDeposit(false);
        user.setDeposit(BigDecimal.ZERO);
        userService.updateById(user);

        memberOrder.setRefundType("线下退款");
        memberOrder.setRefundContent(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",new Date()));
        // 记录订单退款相关信息
        memberOrder.setRefundAmount(memberOrder.getFinalPrice());
        memberOrder.setRefundTime(now);
        memberOrderMapper.updateByPrimaryKeySelective(memberOrder);

        return ResponseUtil.ok();

    }
}
